import { setToken, getToken } from '@/utils/auth'
import { login } from '@/api/user'

const state = {
  token: getToken() || '',
  userInfo: JSON.parse(localStorage.getItem('userInfo'))
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 设置用户信息
  setUserInfo(state, newuserInfo) {
    state.userInfo = newuserInfo
    localStorage.setItem('userInfo', JSON.stringify(newuserInfo))
  }
}
const actions = {
  async login(context, payload) {
    // console.log('login', context, payload)
    const result = await login(payload)
    // console.log(result)
    const token = result.data.data.token.token
    context.commit('setToken', token)
    context.commit('setUserInfo', result.data.data.user)
    console.log(state.userInfo)
  },
  logout(context) {
    context.commit('setToken', '')
    context.commit('setUserInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
